// ==UserScript==
// @name        微信读书自动点下一章
// @namespace   weread auto next
// @match       https://weread.qq.com/web/reader/*
// @grant       none
// @version     1.0
// @author      聪
// @description 2019/12/6 下午10:49:13
// ==/UserScript==

let t1 = 0;
let t2 = 0;
// 定时器
let timer = null;
// 滑动栏是否在最低部
let isLowest = false;
// 文章底部下一章的高度
let NEXT_DIV_HEIGHT = 244;

// 按键绑定
document.onkeydown = (event) => {
  let e = event || window.e;
  let keyCode = e.keyCode || e.which;
  switch (keyCode) {
    // 向左键、向右键
    case 37:
    case 39:
      document.documentElement.scrollTop = 0;
  }
}

/**
 * scroll监听
 */
document.onscroll = () => {
  clearTimeout(timer);
  timer = setTimeout(isScrollEnd, 100);
  t1 = document.documentElement.scrollTop || document.body.scrollTop;
}

/**
 * 滚动条停止时
 */
let isScrollEnd = () => {
  t2 = document.documentElement.scrollTop || document.body.scrollTop;
  if (t2 == t1) {
    autoNext();
  }
}

/**
 * 判断章节是否读完，读完自动点击下一页
 */
let autoNext = () => {
  // 获取页面高度
  let clientHeight = document.body.scrollHeight;
  // 获取屏幕高度
  let windowHeight = document.all ? document.getElementsByTagName("html")[0].offsetHeight : window.innerHeight;
  // 获取滚动条所在高度
  let scrollPosition = document.body.scrollTop | document.documentElement.scrollTop;

  // 防止回看后滚动栏再次到底部
  // 避免自主点击下一章造成的“修改过页面高度未还原及滚动栏还在上章的位置”
  if (isLowest && (scrollPosition + windowHeight) < (clientHeight - 1)) {
    document.getElementsByClassName("app_content")[0].style.height = "auto";
    isLowest = false;
  }

  if (isLowest) {
    let el =  document.getElementsByClassName("readerFooter_button")[0];
    let doc = el.ownerDocument;
    let keyEvent = doc.createEvent('KeyEvents');
    keyEvent.initKeyEvent('keydown', true, true, doc.defaultView, false, false, false, false, 39, 0 );
    el.dispatchEvent(keyEvent);
  }

  // 给章节下面的下一章添加 点击光标移动到顶部
  if ((scrollPosition + windowHeight) >= clientHeight - NEXT_DIV_HEIGHT) {
    document.getElementsByClassName("readerFooter_button")[0].onclick = () => {
      document.documentElement.scrollTop = 0;
    }
  }

  // 判断滚动栏是否到最底部
  if ((scrollPosition + windowHeight) >= clientHeight) {
    document.getElementsByClassName("app_content")[0].style.height = clientHeight + 1 + "px";
    isLowest = true;
  }
}